package com.api.weavernorth.LogWeaTable.service.Impl;

import com.api.weavernorth.LogWeaTable.pojo.logdataPojo;
import com.api.weavernorth.LogWeaTable.service.LogDataService;
import com.weavernorth.util.dateUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import weaver.conn.ConnectionPool;
import weaver.conn.RecordSet;
import weaver.general.Util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: bruseewang
 * @Package: com.api.weavernorth.LogWeaTable.service.Impl
 * @date: 2021/12/8 18:20
 * @description:
 */
public class LogDataServiceImpl implements LogDataService {
    public static ConnectionPool pool = ConnectionPool.getInstance();
    public Connection conn;
    public Statement statement;

    @Override
    public List<logdataPojo> ScanLog(Logger log, Map<String, Object> params, Boolean isAll) {
        String path = "/usr/weaver/ecology";
        LinkedList<File> list = new LinkedList<File>();
        //服务器上日志集合
        List<logdataPojo> logdate_List = new ArrayList<>();
        //配置表中日志路径集合
        List<logdataPojo> list_path = new ArrayList<>();
        //1.查询日志路径配置表
        RecordSet rs = new RecordSet();
        String strQuery = "SELECT * FROM uf_logUrl_cfg where 1=1 ";
        if (!isAll) {
            //查询条件：日志名称
            String logname = Util.null2String(params.get("logname"));
            if (StringUtils.isNotBlank(logname)) {
                strQuery += "and rzmc='" + logname + "'";
            }
            //查询条件：路径类型
            String ljlx = Util.null2String(params.get("ljlx"));
            if (StringUtils.isNotBlank(ljlx)) {
                strQuery += "and ljlx='" + ljlx + "'";
            }
            log.info("查询日志路径配置表：" + strQuery);
        }
        rs.execute(strQuery);
        RecordSet rs_geip=new RecordSet();
        String str_getIp="select sys_context('userenv','host') hostname,sys_context('userenv','ip_address') ip from dual";
        rs_geip.execute(str_getIp);
        String hosts="";
        while (rs_geip.next()){
            hosts=rs_geip.getString("ip");
        }
        String strPath = "";
        String l_LogName = "";
        String l_ljlx = "";
        logdataPojo first_pojo;
        while (rs.next()) {
            strPath = Util.null2String(rs.getString("rzlj"));
            l_LogName = Util.null2String(rs.getString("rzmc"));
            l_ljlx = Util.null2String(rs.getString("ljlx"));
            if (StringUtils.isNotBlank(strPath)) {
                if (strPath.equals("/log/ecology/")) {
                    logdataPojo pojo = new logdataPojo();
                    pojo.setLjlx(l_ljlx);
                    pojo.setLogName(l_LogName);
                    pojo.setLogDate(dateUtils.getYearMonthDay());
                    pojo.setLogLink(strPath + "ecology");
                    pojo.setHosts(hosts);

                    logdate_List.add(pojo);
                } else {
                    first_pojo = new logdataPojo();
                    first_pojo.setLogName(l_LogName);
                    first_pojo.setLjlx(l_ljlx);
                    first_pojo.setHosts(hosts);
                    first_pojo.setLogLink(path + strPath);
                    list_path.add(first_pojo);
                }

            }
        }
        if (list_path.size() > 0) {
            File file;
            File[] files;
            File tempFile;
            String fileName = "";
            String date = "";
            try {
                for (logdataPojo po : list_path) {
                    String newPath = po.getLogLink();
                    file = new File(newPath);

                    if (file.exists()) {
                        files = file.listFiles();
                        for (File thisFile : files) {
                            if (thisFile.isDirectory()) {
                                list.add(thisFile);
                                continue;
                            }
                            fileName = thisFile.getName();
                            date = fileName.substring(0, fileName.indexOf(".log"));
                            if (date.indexOf("-") == -1 && date.length() > 7) {
                                StringBuffer sb = new StringBuffer();
                                sb.append(date);
                                sb.insert(4, "-");
                                sb.insert(7, "-");
                                date = sb.toString();
                            }
                            logdataPojo pojo = new logdataPojo();
                            pojo.setLjlx(po.getLjlx());
                            pojo.setLogName(po.getLogName());
                            pojo.setHosts(po.getHosts());
                            pojo.setLogDate(date);
                            pojo.setLogLink(po.getLogLink() + fileName);
                            logdate_List.add(pojo);

                        }
                        for (Iterator itr = list.iterator(); itr.hasNext(); ) {
                            tempFile = list.removeFirst();
                            for (File thisFile : tempFile.listFiles()) {
                                if (thisFile.isDirectory()) {
                                    list.add(thisFile);
                                    continue;
                                }
                                fileName = thisFile.getName();
                                date = fileName.substring(0, fileName.indexOf(".log"));
                                if (date.indexOf("-") == -1 && date.length() > 7) {
                                    StringBuffer sb = new StringBuffer();
                                    sb.append(date);
                                    sb.insert(4, "-");
                                    sb.insert(7, "-");
                                    date = sb.toString();
                                }
                                logdataPojo pojo = new logdataPojo();
                                pojo.setLjlx(po.getLjlx());
                                pojo.setLogName(po.getLogName());
                                pojo.setHosts(po.getHosts());
                                pojo.setLogDate(date);
                                //File.separator替代斜杠'/'
                                pojo.setLogLink(po.getLogLink() + fileName);
                                logdate_List.add(pojo);

                            }
                        }
                    } else {
                        log.info("该文件将夹为空！！！");
                    }

                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return logdate_List;
    }

    @Override
    public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws IOException {
        File f = new File(filePath);
        if (!f.exists()) {
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        if (isOnLine) { // 在线打开方式
            URL u = new URL("file:///" + filePath);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        br.close();
        out.close();
    }

    /***
     * 查询服务器日志，并将数据表中没有的日志记录插入到数据表
     * @param log
     * @throws SQLException
     */
    @Override
    public List<logdataPojo> Operation_LogData(Logger log, Map<String, Object> params, Boolean isAll) {
        try {
            conn = pool.getConnection();
            statement = conn.createStatement();
            String strSqls = "";
            LogDataServiceImpl logDataService = new LogDataServiceImpl();
            List<logdataPojo> logdataPojoList = null;
            String qeuryDate = Util.null2String(params.get("queryDate"));
            if (isAll) {
                //查询所有日志
                logdataPojoList = logDataService.ScanLog(log, params, isAll);
                log.info("服务器日志结果：" + logdataPojoList);
            } else if (StringUtils.isNotBlank(qeuryDate)) {
                //查询指定日期内的日志
                log.info("查询日期：" + qeuryDate);
                String finalQeuryDate = qeuryDate;
                logdataPojoList = logDataService.ScanLog(log, params, isAll).stream().filter((logdataPojo l) -> finalQeuryDate.equals(l.getLogDate())).collect(Collectors.toList());
                log.info("服务器日志结果(过滤后)：" + logdataPojoList);

            }
            for (logdataPojo pojo : logdataPojoList) {
                Boolean bool_exists = isExists(pojo.getLogName(), pojo.getLogDate(), pojo.getLjlx());
                if (!bool_exists) {
                    strSqls = "insert into uf_LogRecord_Table(logname,hosts,logdate,ljlx,loglink) values ('" + pojo.getLogName() + "','"+pojo.getHosts()+"','" + pojo.getLogDate() + "','" + pojo.getLjlx() + "','" + pojo.getLogLink() + "') ";
                    log.info("插入日志关系到数据库表sql：" + strSqls);
                    statement.addBatch(strSqls);
                }
            }

            Long begin1 = System.currentTimeMillis();
            statement.executeBatch();
            Long end1 = System.currentTimeMillis();
            log.info("批量插入耗时：" + (end1 - begin1) + "(毫秒)");
            conn.close();
            statement.close();
            return logdataPojoList;
        } catch (Exception ex) {
            log.info("对日志操作异常：" + ex.toString());
            return null;
        }

    }

    public Boolean isExists(String logname, String logdate, String ljlx) {
        RecordSet rsQuery = new RecordSet();
        String strQuery = "SELECT 1 FROM uf_LogRecord_Table WHERE logname='" + logname + "' AND LOGDATE='" + logdate + "' AND ljlx='" + ljlx + "'";
        rsQuery.execute(strQuery);
        Boolean result = false;
        while (rsQuery.next()) {
            result = true;
        }
        return result;
    }
}
